from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy import make_url


def get_mysql_conn_url(config):
    """
    :description: 生成sqlalchemy使用的连接url
    :param hy_config: hy_config
    :return: url
    """
    mysql_conn_map = dict(
        dialect="mysql",
        driver="pymysql",
        host=config["MYSQL_HOST"],
        port=config["MYSQL_PORT"],
        database=config["MYSQL_DB"],
        user=config["MYSQL_USER"],
        password=config["MYSQL_PASSWORD"],
    )
    s = "{dialect}+{driver}://{user}:{password}@{host}:{port}/{database}?charset=utf8".format(**mysql_conn_map)
    # s = "{dialect}+{driver}://{user}:{password}@{host}:{port}/{database}".format(**mysql_conn_map)
    url = make_url(s)
    print(s)
    return url


def create_mysql_ORM(app):
    """
    创建MySQL的ORM对象并反射数据库中已存在的表，获取所有存在的表对象
    :param app: app:flask实例
    :return: (db:orm-obj, all_table:数据库中所有已存在的表的对象(dict))
    """
    # 创建mysql连接对象
    url = get_mysql_conn_url(config=app.config)
    app.config["SQLALCHEMY_DATABASE_URI"] = url

    # 获取SQLAlchemy实例对象
    db = SQLAlchemy(app)

    # 反射数据库中已存在的表，并获取所有存在的表对象。
    db.reflect()
    all_table = {table_obj.name:
                 table_obj for table_obj in db.get_tables_for_bind()}

    return db, all_table


def init_app(app):
    return create_mysql_ORM(app)
